use yew::prelude::*;

use crate::api;
use crate::component::header::Header;
use crate::component::message_list::MessageList;
use crate::component::message_view::MessageView;
use crate::Message;
use crate::MessageEvent;
use crate::State;
use futures::StreamExt;
use gloo_dialogs::confirm;
use gloo_net::http::Request;
use gloo_net::websocket::{self, futures::WebSocket};
use wasm_bindgen_futures::spawn_local;
use yewdux::prelude::*;

use std::sync::Once;
use web_sys::HtmlTableCellElement;

static WS_ONCE: Once = Once::new();

#[function_component]
pub fn Root() -> Html {
    let (state, dispatch) = use_store::<State>();

    // 清除消息处理
    let clear_onclick = {
        let dispatch = dispatch.clone();

        Callback::from(move |_: MouseEvent| {
            if confirm("Do you want to clear all messages?") {
                api::delete_messages();

                dispatch.reduce_mut(|state| {
                    state.messages.clear();
                    state.selected_message = None;
                });
            }
        })
    };

    // 消息列表点击处理
    let onclick = {
        let state = state.clone();
        let dispatch = dispatch.clone();

        Callback::from(move |e: MouseEvent| {
            let element: HtmlTableCellElement = e.target_unchecked_into();
            
            // 获取父元素
            let parent = match element.parent_element() {
                Some(p) => p,
                None => {
                    log::error!("No parent element found for message row");
                    return;
                }
            };
            
            // 获取消息ID属性
            let id_str = match parent.get_attribute("data-message-id") {
                Some(id) => id,
                None => {
                    log::error!("Parent element missing 'data-message-id' attribute");
                    return;
                }
            };
            
            // 解析消息ID
            let id = match id_str.parse::<usize>() {
                Ok(num) => num,
                Err(e) => {
                    log::error!("Failed to parse message ID '{}': {}", id_str, e);
                    return;
                }
            };

            // 选择消息
            if let Some(message) = state.messages.get(&id) {
                dispatch.reduce_mut(|state| state.selected_message = Some(message.clone()));
            } else {
                log::warn!("Message with ID {} not found in state", id);
            }
        })
    };

    // 加载已有消息
    {
        let dispatch = dispatch.clone();

        use_effect_with((), move |_| {
            spawn_local(async move {
                // 发送请求获取消息
                let response = match Request::get("/api/messages").send().await {
                    Ok(res) => res,
                    Err(e) => {
                        log::error!("Failed to send messages fetch request: {}", e);
                        return;
                    }
                };

                // 解析消息JSON
                let fetched_messages: Vec<Message> = match response.json().await {
                    Ok(msgs) => msgs,
                    Err(e) => {
                        log::error!("Failed to parse fetched messages: {}", e);
                        return;
                    }
                };

                // 更新状态
                dispatch.reduce_mut(|state| {
                    for message in fetched_messages {
                        if let Some(id) = message.id {
                            state.messages.insert(id, message.clone());
                        } else {
                            log::warn!("Skipping message with missing ID");
                        }
                    }
                });
            });
        });
    }

    // 启动WebSocket连接
    {
        let dispatch = dispatch.clone();
        WS_ONCE.call_once(move || {
            // 获取窗口对象
            let window = match web_sys::window() {
                Some(w) => w,
                None => {
                    log::error!("Failed to get browser window object");
                    return;
                }
            };

            // 获取当前URL
            let href = match window.location().href() {
                Ok(h) => h,
                Err(e) => {
                    log::error!("Failed to get current location href: {:?}", e);
                    return;
                }
            };

            // 解析URL
            let mut url = match url::Url::parse(&href) {
                Ok(u) => u,
                Err(e) => {
                    log::error!("Failed to parse current URL '{}': {}", href, e);
                    return;
                }
            };

            // 设置WebSocket协议
            if url.scheme() == "https" {
                url.set_scheme("wss").expect("Failed to set WSS scheme");
            } else {
                url.set_scheme("ws").expect("Failed to set WS scheme");
            }
            url.set_path("/ws");

            // 建立WebSocket连接
            let ws = match WebSocket::open(url.as_ref()) {
                Ok(ws) => ws,
                Err(e) => {
                    log::error!("Failed to open WebSocket connection to '{}': {}", url, e);
                    return;
                }
            };

            let (_, mut read) = ws.split();
            let dispatch = dispatch.clone();

            // 处理WebSocket消息
            spawn_local(async move {
                while let Some(msg) = read.next().await {
                    match msg {
                        Ok(websocket::Message::Text(msg_str)) => {
                            match serde_json::from_str::<MessageEvent>(&msg_str) {
                                Ok(event) => {
                                    if let Some(msg_id) = event.message.id {
                                        dispatch.reduce_mut(|state| {
                                            state.messages.insert(msg_id, event.message)
                                        });
                                    } else {
                                        log::warn!("Received message with missing ID");
                                    }
                                }
                                Err(e) => {
                                    log::error!("Failed to parse WebSocket message: {}", e);
                                }
                            }
                        }
                        Ok(_) => log::warn!("Received non-text WebSocket message"),
                        Err(e) => log::error!("WebSocket error: {}", e),
                    }
                }
                log::info!("WebSocket connection closed");
            });
        });
    }

    // 渲染组件
    html! {
        <>
            <Header clear_onclick={clear_onclick} />
            <div class="main">
                <MessageList {onclick} />
                <MessageView />
            </div>
        </>
    }
}
